package com.xn.app.muying.activity;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.xn.app.muying.R;
import com.xn.app.muying.adpter.HealthRecordsDateAdapter;
import com.xn.app.muying.adpter.HealthRecordsHistoryAdapter;
import com.xn.app.muying.bean.HealthRecordsListBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import okhttp3.Request;

/**
 * 年度历史查询健康档案
 * Created by Administrator on 2017/5/3.
 */
public class HealthRecordsHistoryActivity extends BaseActivity implements View.OnClickListener {
    //数据库
    private DBManager db = null;
    //标题文字
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    //显示的日期
    private TextView year;
    //选择日期图标
    private ImageView time;
    private MyListView lv;
    private HealthRecordsHistoryAdapter adapter;
    //加载框
    AlertDialog dialog;
    //就诊人就诊信息
    private ArrayList<HealthRecordsListBean> list = null;
    private String jzrqsj;
    private LinearLayout nodata;
    private MyAlertDialog myAlertDialog;
    //用来查询的年份
    private String yearStr = Calendar.getInstance().get(Calendar.YEAR) + "";
    //功能最初年份
    private final int initYear = 2016;

    ArrayList<String> yearList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_healthrecordshistory);
        db = new DBManager(this);
        if (NetworkUtil.isNetworkAvailable(this)) {
            initView();
            VisitReportLoading(getIntent().getStringExtra("identityId"), getIntent().getStringExtra("fullname"));
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }
    }

    private void initView() {
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        year = (TextView) findViewById(R.id.healthrecordshistory_year);
        time = (ImageView) findViewById(R.id.healthrecordshistory_time);
        lv = (MyListView) findViewById(R.id.healthrecordshistory_listview);
        nodata = (LinearLayout) findViewById(R.id.nodata_linearlayout);
        title_name.setText("年度健康档案");
        img_back.setOnClickListener(this);
        time.setOnClickListener(this);
        year.setText(yearStr + "年度");
        adapter = new HealthRecordsHistoryAdapter(this);
        lv.setAdapter(adapter);
        //lv点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list != null&&position<list.size()) {
                    Intent intent = new Intent();
                    intent.putExtra("registerID", list.get(position).getRegisterID());
                    intent.setClass(HealthRecordsHistoryActivity.this, HealthRecordsCategoryActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    private void VisitReportLoading(final String identityId, final String fullname) {
        dialog = new MyAlertDialog().ShowDialog(HealthRecordsHistoryActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.VisitReport(identityId, fullname)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 0:
                    onJsonVisitReportData(msg.obj.toString());
                    break;

            }
        }
    };

    //列表数据整理
    private void onJsonVisitReportData(String s) {
        try {
            JSONObject jsonObject = new JSONObject(s);
            JSONArray items = jsonObject.getJSONArray("items");
            list = new ArrayList<>();
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String id = object.optString("id");
                jzrqsj = object.optString("jzrqsj");
                String jzksmc = object.optString("jzksmc");
                String zrys = object.optString("zrys");
                String zryszc = object.optString("zryszc");
                String hospital = object.optString("hospital");
                String inpid = object.optString("inpid");
                String registerID = object.optString("registerID");
                HealthRecordsListBean healthRecordsListBean = new HealthRecordsListBean();
                String[] strs = new String[0];
                strs = jzrqsj.split("T")[0].split("-");
                if (strs[0].equals(yearStr)) {
                    healthRecordsListBean.setId(id);
                    healthRecordsListBean.setJzrqsj(jzrqsj);
                    healthRecordsListBean.setJzksmc(jzksmc);
                    healthRecordsListBean.setZrys(zrys);
                    healthRecordsListBean.setZryszc(zryszc);
                    healthRecordsListBean.setHospital(hospital);
                    healthRecordsListBean.setInpid(inpid);
                    healthRecordsListBean.setRegisterID(registerID);
                    list.add(healthRecordsListBean);
                }
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (jzrqsj != null && list.size() != 0) {
                        nodata.setVisibility(View.GONE);
                        lv.setVisibility(View.VISIBLE);
                    } else {
                        nodata.setVisibility(View.VISIBLE);
                        lv.setVisibility(View.GONE);
                    }
                }
            });
            adapter.getData(list);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.healthrecordshistory_time:
                if (yearList != null && yearList.size() > 0) {
                    //不做处理
                } else {
                    //处理年份
                    yearList = new ArrayList<>();
                    for (int i = initYear; i <= Calendar.getInstance().get(Calendar.YEAR); i++) {
                        yearList.add(i + "年");
                    }
                }
                //日期弹出框
                final PopupWindow window = new PopupWindow(this);
                View view = getLayoutInflater().inflate(R.layout.popupwindow, null);
                window.setContentView(view);
                ColorDrawable dw = new ColorDrawable(0x00000000);
                window.setBackgroundDrawable(dw);
                ListView lv = (ListView) view.findViewById(R.id.lv);
                HealthRecordsDateAdapter adapter = new HealthRecordsDateAdapter(this, yearList);
                lv.setAdapter(adapter);
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        yearStr = yearList.get(position).replace("年", "");
                        year.setText(yearStr + "年度");
                        nodata.setVisibility(View.GONE);
                        VisitReportLoading(getIntent().getStringExtra("identityId"), getIntent().getStringExtra("fullname"));
                        window.dismiss();
                    }
                });
                window.setOutsideTouchable(true);
                window.setFocusable(false);
                window.setWidth(300);
                if (yearList.size() == 1) {
                    window.setHeight(180);
                } else if (yearList.size() == 2) {
                    window.setHeight(300);
                } else if (yearList.size() > 2) {
                    window.setHeight(400);
                }

                window.showAsDropDown(v, 0, 0);
                break;
        }
    }
}
